package MetroMessenger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class MessageReceiver implements Runnable
{
   private BufferedReader input; 
   private MessageListener messageListener;
   private boolean keepListening = true; 
   
   public MessageReceiver( MessageListener listener, Socket clientSocket ) 
   {
      messageListener = listener;
      
      try 
      {
         clientSocket.setSoTimeout( 5000 ); 
         input = new BufferedReader( new InputStreamReader(clientSocket.getInputStream() ) );
      }
      catch ( IOException ioException ) 
      {
         ioException.printStackTrace();
      }
   } 
   public void run() 
   
   {    
      String message;
      while ( keepListening ) 
      {   
         try 
         {            
            message = input.readLine(); 
         } 
         catch ( SocketTimeoutException socketTimeoutException ) 
         {
            continue;
         } 
         catch ( IOException ioException ) 
         {
            ioException.printStackTrace();            
            break;
         } 
         if ( message != null ) 
         {
            messageListener.messageReceived( message );  
         }
      }   
      
      try
      {         
         input.close(); 
      } 
      catch ( IOException ioException ) 
      {
         ioException.printStackTrace();     
      } 
   } 
   public void stopListening() 
   {
      keepListening = false;
   } 
}